/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\StatementOfAccount\SendStatementOfAccount\components\StatementOfAccountInfo.tsx
 * @Date: 2022-03-15 11:53:05
 * @LastEditTime: 2022-04-08 18:32:25
 */

import { columnRenders, http, IUdColumn, UdModal, UdTable } from '@/lib'
import { useBoolean, useMount, useSafeState, useUpdateEffect } from 'ahooks'
import { InputNumber, message, Modal, Switch } from 'antd'
import React, { useCallback, useImperativeHandle } from 'react'
import apis from '@/apis/StatementOfAccount/index'

interface IProps {
  distributorList: Record<string, any>[]
  values: Record<string, any>
  ref?: any
}

const StatementOfAccountInfo = (props: IProps) => {
  const [dataSource, setTableData] = useSafeState<any[]>([])
  const [loading, setLoading] = useSafeState<boolean>(false)
  const [checked, { toggle }] = useBoolean(false)
  const [selectedRowKeys, setSelectedRowKeys] = useSafeState<any[]>([])
  const [selectedRows, setSelectedRows] = useSafeState<Record<string, any>[]>([])
  const [pagination, setPagination] = useSafeState<Record<string, any>>({})

  useUpdateEffect(() => {
    getTableData()
  }, [checked])

  useMount(() => {
    getTableData()
  })

  const getTableData = async () => {
    const { distributorList = [] } = props
    const { brandCode, launchTime, templateModelId, letterName } = props.values
    setLoading(true)
    let params = {
      brandCode,
      type: Number(checked),
      letterName,
      launchTime,
      templateModelId,
      agentRspVoList: distributorList,
    }
    try {
      let list: any = await http.post(apis.getLetterLaunchInfo, params)
      const dataSource = list?.data ?? []
      setTableData(dataSource)
      setLoading(false)
      setPagination({
        current: 1,
        pageSize: 5,
        total: dataSource.length ?? 0,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '20', '30', '40'],
        showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
      })
    } catch (error) {
      setLoading(false)
    }
  }

  const renderInput = (text, record, field): any => {
    return (
      <InputNumber
        style={{ width: '100%' }}
        value={text}
        step={'0.01'}
        min={0}
        formatter={value => {
          const reg = /^(-)*(\d+)\.(\d\d).*$/
          const val = String(value).replace(reg, '$1$2.$3')
          return val
        }}
        parser={value => {
          const reg = /^(-)*(\d+)\.(\d\d).*$/
          const val = String(value).replace(reg, '$1$2.$3')
          return val
        }}
        onChange={value => inputChange(value, record, field)}
      />
    )
  }

  const inputChange = (value, record, field): void => {
    let index = dataSource.findIndex(item => item.id === record.id)
    let newDataSource = [...dataSource]
    newDataSource[index][field] = value
    setTableData(newDataSource)
  }

  const onSelectChange = (selectedRowKeys: number[], selectedRows: Record<string, any>[]) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const onSelectAll = (selected, selectedRows, changeRows) => {
    if (selected) {
      setSelectedRows(dataSource)
      setSelectedRowKeys(dataSource.map(({ id }) => id))
    }
  }

  const calcColumns = () => {
    let recordItem = dataSource[0]
    let restColumn: IUdColumn<any>[] = []
    if (recordItem) {
      let keys = Object.keys(recordItem)
      let columnKeys = keys.filter(key => key.includes('value_'))
      for (let key of columnKeys) {
        let values: string[] = key.split('_')
        restColumn.push({
          title: values[1],
          key: values[1],
          dataIndex: values.join('_'),
          minWidth: '70px',
          render: (text: any, record: any, index: number) => {
            if (values[3] === '1') {
              return renderInput(text, record, values.join('_'))
            } else {
              return text
            }
          },
        })
      }
    }
    let columns: IUdColumn<any>[] = [
      {
        title: '序号',
        dataIndex: 'id',
        key: 'id',
        width: '50px',
        render: (text, reoled, index) => index + 1,
      },
      { title: '经销商编码', key: 'dealerCode', dataIndex: 'dealerCode', minWidth: '70px' },
      { title: '经销商名称', key: 'dealerName', dataIndex: 'dealerName', minWidth: '160px' },
      { title: '品牌公司', key: 'brandName', dataIndex: 'brandName', minWidth: '160px' },
      ...restColumn,
      { title: '截止日期', key: 'launchTime', dataIndex: 'launchTime', minWidth: '60px' },
      {
        title: '操作',
        dataIndex: 'operate',
        width: '130',
        fixed: 'right',
        render: columnRenders.operate([
          {
            title: '删除',
            action: (text, record) => {
              Modal.confirm({
                title: '删除',
                content: `确定删除${record.brandName}吗`,
                okType: 'danger',
                onOk: () => {
                  let index = dataSource.findIndex(item => item.id === record.id)
                  let newDataSource = [...dataSource]
                  newDataSource.splice(index, 1)
                  setTableData(newDataSource)
                  setSelectedRowKeys(selectedRowKeys.filter(item => item !== record.id))
                  setSelectedRows(selectedRows.filter(item => item.id !== record.id))
                  setPagination({
                    current: 1,
                    pageSize: 5,
                    total: newDataSource.length ?? 0,
                    showSizeChanger: true,
                    pageSizeOptions: ['5', '10', '20', '30', '40'],
                    showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
                  })
                },
              })
            },
          },
          {
            title: '预览',
            action: (text, record) => handTemplateView(record),
          },
        ]),
      },
    ]
    return columns
  }

  const memoizedCalcColumns = useCallback(calcColumns, [dataSource])

  const handTemplateView = (record: { modelUrl: string; modelFileName: string }): void => {
    const rex = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/
    const { modelUrl, modelFileName } = record
    if (rex.test(modelUrl)) {
      UdModal.open({
        title: modelFileName,
        width: '80%',
        bodyStyle: { padding: '0' },
        content: (
          <div style={{ height: '700px', overflow: 'hidden' }}>
            <iframe
              title={modelFileName}
              src={`https://view.officeapps.live.com/op/view.aspx?src=${modelUrl}`}
              width="100%"
              height="100%"
              frameBorder="0"
              style={{ border: 'none' }}
              seamless
            ></iframe>
          </div>
        ),
        footer: null,
      })
    } else {
      message.error('附件URL无效')
    }
  }

  return (
    <>
      <div style={{ marginBottom: '10px' }}>
        <span style={{ color: '#999', marginRight: '10px' }}>过滤与上期对账金额相同的经销商</span>
        <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked={checked} onClick={toggle} />
      </div>
      <UdTable
        rowKey="id"
        scroll={{ x: true }}
        loading={loading}
        columns={memoizedCalcColumns()}
        dataSource={dataSource}
        pagination={pagination}
        rowSelection={{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          onSelectAll: onSelectAll,
        }}
        onChange={paginationOpt => {
          setPagination(paginationOpt)
        }}
      />
    </>
  )
}
const StatementOfAccountInfoRef = React.forwardRef((props: IProps, ref) => {
  // let selectedRows = {...selectedRows}
  useImperativeHandle(ref, () => ({
    onOk: e => {
      // let arr = selectedRows.map(item => {
      //   let obj = { ...item }
      //   obj.letterName = props.values.letterName
      //   obj.values = '111'
      //   return obj
      // })
      let params = {}
      // console.log('arr :>> ', arr)
      // http.post(apis.saveLetterLaunchInfo, params).then(res => {
      //   message.success('操作成功')
      //   e.close()
      // })
    },
  }))
  return <StatementOfAccountInfo {...props} />
})
export default React.memo(StatementOfAccountInfoRef)
